<template>
  <el-container class="official-account-management_custom-menu">
    <el-main>
      <el-card shadow="never" class="tableCard">
        <div v-loading="saveLoading" class="public-account-management clearfix">
          <!--左边配置菜单-->
          <div class="left">
            <div class="weixin-hd">
              <div class="weixin-title">{{ menuName }}</div>
            </div>
            <div class="weixin-menu menu_main clearfix">
              <div v-for="(item, i) of menu.buttons" :key="i" class="menu_bottom">
                <!-- 一级菜单 -->
                <div class="menu_item el-icon-s-fold" :class="{'active': isActive == i}" @click="menuFun(i,item)">{{ item.name }}</div>
                <!--以下为二级菜单-->
                <div v-if="isSubMenuFlag == i" class="submenu">
                  <div v-for="(subItem, k) in item.subButtons" v-show="item.subButtons" :key="k" class="subtitle menu_bottom">
                    <div class="menu_subItem" :class="{'active': isSubMenuActive == i + '' +k}" @click="subMenuFun(subItem, i, k)">{{ subItem.name }}</div>
                  </div>
                  <!--  二级菜单加号， 当长度 小于  5 才显示二级菜单的加号  -->
                  <div v-if="!item.subButtons || item.subButtons.length < 5" class="menu_bottom menu_addicon" @click="addSubMenu(i,item)"><i class="el-icon-plus" /></div>
                </div>
              </div>
              <!-- 一级菜单加号 -->
              <div v-if="menuKeyLength < 3" class="menu_bottom menu_addicon" @click="addMenu"><i class="el-icon-plus" /></div>
            </div>
            <div class="save_div">
              <el-button class="save_btn" type="success" size="small" @click="saveAndReleaseFun">保存并发布菜单</el-button>
            </div>
          </div>
          <!--右边配置-->
          <div v-if="showRightFlag" class="right">
            <div class="configure_page">
              <div class="delete_btn">
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteMenu(tempObj)">删除当前菜单</el-button>
              </div>
              <el-form ref="form" label-position="right" label-width="9rem">
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="菜单名称：">
                      <el-input v-model="tempObj.name" class="input_width" placeholder="请输入菜单名称" :maxlength="nameMaxlength" clearable />
                    </el-form-item>
                  </el-col>
                  <div v-if="showConfigurContent">
                    <el-col :span="24">
                      <el-form-item label="菜单内容：">
                        <el-select v-model="tempObj.eventType" clearable placeholder="请选择" class="menu_option" @change="contentUpdate">
                          <el-option v-for="item in menuOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="tempObj.eventType == 'VIEW'" :span="24">
                      <el-form-item label="跳转链接：">
                        <el-input v-model="tempObj.hrefUrl" class="input_width" placeholder="请输入链接，以http(s)://开头" clearable @change="tempObj.unionKey = tempObj.hrefUrl" />
                      </el-form-item>
                    </el-col>
                    <div v-if="tempObj.eventType == 'MINIPROGRAM'">
                      <el-col :span="24">
                        <el-form-item label="小程序的appid：">
                          <el-select v-model="tempObj.unionKey">
                            <el-option v-for="item in minList" :key="item.id" :label="item.name" :value="item.id.toString()" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="小程序的页面路径：">
                          <el-input v-model="tempObj.route" class="input_width" placeholder="请输入小程序的页面路径，如：pages/index" clearable />
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="备用网页：">
                          <div style="width: 100%">
                            <el-input v-model="tempObj.h5" class="input_width" placeholder="不支持小程序的老版本客户端将打开本网页" clearable />
                            <p class="blue">tips:需要和公众号进行关联才可以把小程序绑定带微信菜单上哟！</p>
                          </div>
                        </el-form-item>
                      </el-col>
                    </div>
                    <div v-if="tempObj.eventType === 'VIEW_LIMITED' || tempObj.eventType === 'MEDIA_ID'">
                      <el-col v-if="imageTextParams && imageTextParams.length >0" :span="24">
                        <el-form-item label="选择图文：">
                          <div>
                            <WxNews :obj-data="imageTextParams" />
                            <el-row class="ope-row">
                              <el-button type="danger" icon="el-icon-delete" circle @click="deleteTempObj" />
                            </el-row>
                          </div>
                        </el-form-item>
                      </el-col>
                      <el-col v-else :span="24">
                        <el-form-item label="选择图文：">
                          <el-button type="success" @click="openMaterial">素材库选择<i class="el-icon-circle-check el-icon--right" /></el-button>
                        </el-form-item>
                      </el-col>
                      <el-dialog title="选择图文" :close-on-click-modal="false" :visible.sync="dialogNewsVisible">
                        <WxMaterialSelect :obj-data="{sourceType:'IMAGE_TEXT', appId: params.appId}" @selectMaterial="selectMaterial" />
                      </el-dialog>
                    </div>
                    <el-col v-if="tempObj.eventType == 'CLICK' || tempObj.eventType == 'SCANCODE_WAIT_MSG'" :span="24">
                      <el-form-item label="回复内容：">
                        <WxReplySelect v-if="hackResetWxReplySelect" :obj-data="tempObj" @updateMenu="updateMenu" />
                      </el-form-item>
                    </el-col>
                  </div>
                </el-row>
              </el-form>
            </div>
          </div>
          <!--一进页面就显示的默认页面，当点击左边按钮的时候，就不显示了-->
          <div v-if="!showRightFlag" class="right">
            <p>请选择菜单配置</p>
          </div>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script>
import WxReplySelect from '@/components/wechat-mp/wx-reply-menu/main.vue'
import WxNews from '@/components/wechat-mp/wx-news-menu/main.vue'
import WxMaterialSelect from '@/components/wechat-mp/wx-material-menu-select/main.vue'
import { checkVaildWxMp, saveAndRelease, getList, getMinList as getMinMenuList } from '@/api/wxMp'

export default {
  components: { WxReplySelect, WxNews, WxMaterialSelect },
  data() {
    return {
      params: {
        appId: ''
      },
      afterParams: {
        appId: ''
      },
      showRightFlag: false, // 右边配置显示默认详情还是配置详情
      imageTextParams: [],
      menu: {
        buttons: []
      }, // 横向菜单
      isActive: -1, // 一级菜单点中样式
      isSubMenuActive: -1, // 一级菜单点中样式
      isSubMenuFlag: -1, // 二级菜单显示标志
      tempObj: {
        sourceType: 'TEXT',
        type: ''
      }, // 右边临时变量，作为中间值牵引关系
      tempSelfObj: {}, // 一些临时值放在这里进行判断，如果放在tempObj，由于引用关系，menu也会多了多余的参数
      visible2: false, // 素材内容  "选择素材"按钮弹框显示隐藏
      tableData: [], // 素材内容弹框数据,
      menuName: '',
      showConfigurContent: true,
      nameMaxlength: 0, // 名称最大长度
      menuOptions: [
        { value: 'VIEW', label: '跳转网页' },
        { value: 'MINIPROGRAM', label: '跳转小程序' },
        { value: 'CLICK', label: '点击回复' },
        { value: 'VIEW_LIMITED', label: '跳转图文消息' },
        { value: 'SCANCODE_PUSH', label: '扫码直接返回结果' },
        { value: 'SCANCODE_WAIT_MSG', label: '扫码回复' },
        { value: 'PIC_SYS_PHOTO', label: '系统拍照发图' },
        { value: 'PIC_PHOTO_OR_ALBUM', label: '拍照或者相册' },
        { value: 'PIC_WEI_XIN', label: '微信相册' },
        { value: 'LOCATION_SELECT', label: '选择地理位置' },
        { value: 'MEDIA_ID', label: '图文' }
      ],
      dialogNewsVisible: false,
      saveLoading: false,
      hackResetWxReplySelect: false,
      minList: []
    }
  },
  computed: {
    // menuObj的长度，当长度 小于  3 才显示一级菜单的加号
    menuKeyLength: function() {
      return this.menu.buttons.length
    }
  },
  created() {
    this.init()
    this.getMinList()
  },
  methods: {
    getMinList() {
      getMinMenuList({}).then(response => {
        this.minList = response
      })
    },
    refreshParams(params) {
      this.params = params
      this.getList1()
    },
    init() {
      checkVaildWxMp().then(res => {
        this.params.appId = res.appId
        this.afterParams.appId = res.appId
        alert(res.appId)
        this.getList()
      })
    },
    getList1() {
      this.afterParams.appId = this.params.appId
      this.getList()
    },
    deleteTempObj() {
      this.$set(this.tempObj, 'unionKey', '')
      this.imageTextParams = []
    },
    openMaterial() {
      this.dialogNewsVisible = true
    },
    selectMaterial(item) {
      if (item.mpSourceNewsPageVos.length > 1) {
        this.$alert('您选择的是多图文，将默认跳转第一篇', '提示', {
          confirmButtonText: '确定'
        })
      }
      this.imageTextParams = item.mpSourceNewsPageVos
      this.dialogNewsVisible = false
      this.tempObj.unionKey = item.id
    },
    getList() {
      getList({ id: this.params.appId }).then((res) => {
        this.menu.buttons = res.buttons === null ? [] : res.buttons
      })
    },
    handleClick(tab, event) {
      this.tempObj.mediaType = tab.name
    },
    saveAndReleaseFun() {
      this.$confirm('确定要保证并发布该菜单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.saveLoading = true
        saveAndRelease({
          buttons: this.menu.buttons,
          appId: this.afterParams.appId
        }).then(response => {
          this.saveLoading = false
          this.$message({
            showClose: true,
            message: '发布成功',
            type: 'success'
          })
        }).catch(() => {
          this.saveLoading = false
        })
      }).catch(() => {
      })
    },
    updateMenu(newData) {
      if (newData.lev === '1') {
        this.$set(this.menu.buttons, newData.index1, newData)
      } else {
        this.$set(this.menu.buttons[newData.index1].subButtons, newData.index2, newData)
      }
    },
    contentUpdate() {
      if (this.tempObj.eventType === 'MINIPROGRAM') {
        this.getMinList()
      }
      this.imageTextParams = []
      this.$set(this.tempObj, 'unionKey', '')
      this.$set(this.tempObj, 'h5', '')
      this.$set(this.tempObj, 'hrefUrl', '')
      this.$set(this.tempObj, 'route', '')
      this.$set(this.tempObj, 'sourceType', 'TEXT')
      this.hackResetWxReplySelect = false // 销毁组件
      this.$nextTick(() => {
        this.hackResetWxReplySelect = true// 重建组件
      })
    },
    // 一级菜单点击事件
    menuFun(i, item) {
      this.hackResetWxReplySelect = false // 销毁组件
      this.$nextTick(() => {
        this.hackResetWxReplySelect = true// 重建组件
      })
      this.showRightFlag = true // 右边菜单
      this.tempObj = item // 这个如果放在顶部，flag会没有。因为重新赋值了。
      this.tempObj.index1 = i
      this.tempObj.lev = '1'
      this.tempObj.appId = this.params.appId
      if (item.eventType && item.eventType === 'VIEW') {
        this.tempObj.hrefUrl = item.unionKey
      }
      if (item.mpSourceNewsPageVos && (item.eventType === 'SCANCODE_WAIT_MSG' || item.eventType === 'CLICK')) {
        this.tempObj.mpSourceNewsPageVos = item.mpSourceNewsPageVos
      }
      this.tempObj.repUrl = item.unionPath ? item.unionPath : ''
      this.tempObj.repName = item.unionName ? item.unionName : ''
      this.tempObj.sourceType = item.sourceType === undefined ? 'TEXT' : item.sourceType
      this.tempSelfObj.grand = '1' // 表示一级菜单
      this.tempSelfObj.index = i // 表示一级菜单索引
      this.isActive = i // 一级菜单选中样式
      this.isSubMenuFlag = i // 二级菜单显示标志
      this.isSubMenuActive = -1 // 二级菜单去除选中样式
      this.nameMaxlength = 4
      if (item.subButtons && item.subButtons.length > 0) {
        this.showConfigurContent = false
      } else {
        this.showConfigurContent = true
      }
    },
    // 二级菜单点击事件
    subMenuFun(subItem, index, k) {
      this.hackResetWxReplySelect = false // 销毁组件
      this.$nextTick(() => {
        this.hackResetWxReplySelect = true // 重建组件
      })
      this.showRightFlag = true // 右边菜单
      this.tempObj = subItem // 将点击的数据放到临时变量，对象有引用作用
      this.tempObj.index1 = index
      this.tempObj.index2 = k
      this.tempObj.lev = '2'
      this.tempObj.appId = this.params.appId
      this.tempObj.repUrl = subItem.unionPath ? subItem.unionPath : ''
      this.tempObj.repName = subItem.unionName ? subItem.unionName : ''
      this.tempObj.sourceType = subItem.sourceType === '0' || subItem.sourceType === undefined ? 'TEXT' : subItem.sourceType
      if (subItem.eventType && subItem.eventType === 'VIEW') {
        this.tempObj.hrefUrl = subItem.unionKey
      }
      if (subItem.mpSourceNewsPageVos && (subItem.eventType === 'SCANCODE_WAIT_MSG' || subItem.eventType === 'CLICK')) {
        this.tempObj.mpSourceNewsPageVos = subItem.mpSourceNewsPageVos
      }
      this.tempSelfObj.grand = '2' // 表示二级菜单
      this.tempSelfObj.index = index // 表示一级菜单索引
      this.tempSelfObj.secondIndex = k // 表示二级菜单索引
      this.isSubMenuActive = index + '' + k // 二级菜单选中样式
      this.isActive = -1 // 一级菜单去除样式
      this.showConfigurContent = true
      this.nameMaxlength = 7
    },
    // 添加横向一级菜单
    addMenu() {
      const menuKeyLength = this.menuKeyLength
      const addButton = {
        name: '菜单名称',
        subButtons: []
      }
      this.$set(this.menu.buttons, menuKeyLength, addButton)
      this.menuFun(this.menuKeyLength - 1, addButton)
    },
    // 添加横向二级菜单
    addSubMenu(i, item) {
      if (!item.subButtons || item.subButtons.length <= 0) {
        this.$set(item, 'subButtons', [])
        this.$delete(item, 'sourceType')
        this.$delete(item, 'eventType')
        this.$delete(item, 'h5')
        this.$delete(item, 'unionKey')
        this.$delete(item, 'route')
        this.$delete(item, 'remark')
        this.showConfigurContent = false
      }
      this.$set(item, 'eventType', 'CLICK')
      const subMenuKeyLength = item.subButtons.length // 获取二级菜单key长度
      const addButton = { name: '子菜单名称' }
      this.$set(item.subButtons, subMenuKeyLength, addButton)
      this.subMenuFun(item.subButtons[subMenuKeyLength], i, subMenuKeyLength)
    },
    // 删除当前菜单
    deleteMenu(obj) {
      // const _this = this
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // _this.deleteData()// 删除菜单数据
        // _this.tempObj = {}
        // _this.showRightFlag = false
        // this.isActive = -1
        // this.isSubMenuActive = -1
        if (obj.lev === '1') {
          this.menu.buttons = this.menu.buttons.filter((item, index) => index !== obj.index1)
        } else {
          this.menu.buttons[obj.index1].subButtons = this.menu.buttons[obj.index1].subButtons.filter((item, index) => index !== obj.index2)
        }
      }).catch(() => {
      })
    },
    // 删除菜单数据
    deleteData() {
      // 一级菜单的删除方法
      if (this.tempSelfObj.grand === '1') {
        this.menu.buttons.splice(this.tempSelfObj.index, 1)
      }
      // 二级菜单的删除方法
      if (this.tempSelfObj.grand === '2') {
        this.menu.buttons[this.tempSelfObj.index].subButtons.splice(this.tempSelfObj.secondIndex, 1)
      }
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
    }
  }
}
</script>

<style lang="scss">
.official-account-management_custom-menu {}
</style>
<style lang="scss" scoped="scoped">
    /* 公共颜色变量 */
    .clearfix{*zoom:1;}
    .clearfix::after{content: "";display: table; clear: both;}
    div{
        text-align: left;
    }
    .weixin-hd{
        color: #fff;
        text-align: center;
        position: relative;
        bottom: 426px;
        left:0px;
        width: 300px;
        height:64px;
        background: transparent url(assets/menu_head.png) no-repeat 0 0;
        background-position: 0 0;
        background-size: 100%
    }
    .weixin-title{
        color:#fff;
        font-size:14px;
        width:100%;
        text-align: center;
        position:absolute;
        top: 33px;
        left: 0px;
    }
    .weixin-menu{
        background: transparent url(assets/menu_foot.png) no-repeat 0 0;
        padding-left: 43px;
        font-size: 12px
    }
    .menu_option{
        width: 40%!important;
    }
    .public-account-management{
        display: flex;
        margin: 0 auto;
        .left{
            display: inline-block;
            width: 350px;
            height: 715px;
            background: url("assets/iphone_backImg.png") no-repeat;
            background-size: 100% auto;
            padding: 518px 25px 88px;
            position: relative;
            box-sizing: border-box;
            /*第一级菜单*/
            .menu_main{
                .menu_bottom{
                    position: relative;
                    float: left;
                    display: inline-block;
                    box-sizing: border-box;
                    width: 85.5px;
                    text-align: center;
                    border: 1px solid #ebedee;
                    background-color: #fff;
                    cursor: pointer;
                    &.menu_addicon{
                        height: 46px;
                        line-height: 46px;
                    }
                    .menu_item{
                        height: 44px;
                        line-height: 44px;
                        text-align: center;
                        box-sizing: border-box;
                        width: 100%;
                        &.active{
                            border: 1px solid #2bb673;
                        }
                    }
                    .menu_subItem{
                        height: 44px;
                        line-height: 44px;
                        text-align: center;
                        box-sizing: border-box;
                        &.active{
                            border: 1px solid #2bb673;
                        }
                    }
                }
                i{
                    color:#2bb673;
                }
                /*第二级菜单*/
                .submenu{
                    position: absolute;
                    width: 85.5px;
                    bottom: 45px;
                    .subtitle{
                        background-color: #fff;
                        box-sizing: border-box;
                    }
                }
            }
            .save_div{
                margin-top: 15px;
                text-align: center;
                .save_btn{
                    bottom: 20px;
                    left: 100px;
                }
            }
        }
        /*右边菜单内容*/
        .right{
            flex: 1;
            background-color: #e8e7e7;
            padding: 20px;
            margin-left: 20px;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            .configure_page{
                .delete_btn{
                    text-align: right;
                    margin-bottom: 15px;
                }
                .menu_content{
                    margin-top: 20px;
                }
                .configur_content{
                    margin-top: 20px;
                    background-color: #fff;
                    padding: 20px 10px;
                    border-radius: 5px
                }
                .blue{
                    color:#29b6f6;
                    margin-top: 10px;
                }
                .applet{
                    margin-bottom: 20px;
                    span{
                        width: 20%;
                    }
                }
                .material{
                    .input_width{
                        width: 30%;
                    }
                    .el-textarea{
                        width: 80%
                    }
                }
            }
        }
    }
</style>
<!--素材样式-->
<style lang="scss" scoped>
    .pagination{
        text-align: right;
        margin-right: 25px;
    }
    .select-item{
        width: 280px;
        padding: 10px;
        margin: 0 auto 10px auto;
        border: 1px solid #eaeaea;
    }
    .select-item2{
        padding: 10px;
        margin: 0 auto 10px auto;
        border: 1px solid #eaeaea;
    }
    .ope-row{
        padding-top: 10px;
        text-align: center;
    }
    .item-name{
        font-size: 12px;
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
        text-align: center;
    }
</style>
